<template>
  <div>
    <!-- 数量统计 金额统计 -->
    <div class="chart-card chart-card-box">
      <!-- 筛选 -->
      <chart-stock-meet-rate-setting @fetchData="fetchData" :chart-option="chartOption" />

      <div class="summary-box">
        <stats-chart-empty v-show="isEmpty">
          暂无数据
        </stats-chart-empty>

        <!-- 图表 -->
        <div v-show="!isEmpty">
          <div class="columnar-chart">
            <div>
              <div class="chart-header flex-space-between">
                <div class="title">
                  {{countInfoData.title}}
                  <span>&nbsp;&nbsp;总：{{countInfoData.all}}</span>
                </div>
                <chart-download 
                  :chart-type="chartType"
                  :chart-data="countInfoData.nameList"
                  type="COUNTSUMMARY"
                  id="countSummary"/>
              </div>
              <div id="countSummary" class="chart-sumary"></div>
            </div>

            <div>
              <div class="chart-header flex-space-between">
                <div class="title">
                  {{amountInfoData.title}}
                  <span>&nbsp;&nbsp;总：￥{{amountInfoData.all}}</span>
                </div>
                <chart-download 
                  :chart-type="chartType"
                  :chart-data="amountInfoData.nameList"
                  type="AMOUNTSUMMARY"
                  id="amountSummary"/>
              </div>
              <div id="amountSummary" class="chart-sumary"></div>
            </div>
          </div>

          <div class="load-more">
            <el-button v-show="hasNextPage && !isEmpty" @click="loadMore" type="text">加载更多</el-button>
            <span v-show="!hasNextPage && !isEmpty" class="color9a9a9a" type="text" disabled>数据加载完毕</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 明细 -->
    <div class="chart-card chart-card-box">
      <el-radio-group @change="incomeProfitChange" v-model="detailRadio">
        <el-radio-button label="0">收入</el-radio-button>
        <el-radio-button label="1">利润</el-radio-button>
      </el-radio-group>

      <div class="bar-chart-box">
        <bar-ranking-chart
          title="备件明细"
          :chart-type="chartType"
          :chart-data="spareIncomeProfit"
          id="spareIncomeProfit"
          type="SPAREINCOME"
          :type-value="true"
          :has-next-page="spareHasNextPage"
          @categoryMore="categoryMore('spareIncomeProfitData')"
        />

        <bar-ranking-chart
          title="服务项目明细"
          :chart-type="chartType"
          :chart-data="serviceIncomeProfit"
          id="serviceIncomeProfit"
          type="SERVICEINCOME"
          :type-value="true"
          :has-next-page="serviceHasNextPage"
          @categoryMore="categoryMore('serviceIncomeProfitData')"
        />
      </div>
    </div>

  </div>
</template>

<script>
import * as echarts5 from 'echarts5';
import { ref, computed, watch, onMounted, reactive, nextTick } from 'vue';
/* component */
import StatsChartEmpty from '@src/modules/report/common/StatsChartEmpty.vue';
import ChartStockMeetRateSetting from './common/ChartStockMeetRateSetting.vue';
import BarRankingChart from './BarRankingChart.vue';
import { ChartDownload } from './common/index';
/* service */
import { openDataCanvasConvertData } from '@service/OpenDataService.ts'
/* util */
import { isOpenData } from '@src/util/platform';

export default {
  name: 'bar-revenue-chart',
  props: {
    sparePartsData: {
      type: Object,
      default: () => ({})
    },
    salesMap: {
      type: Object,
      default: () => ({})
    },
    chartOption: {
      type: Object,
    },
    chartType: {
      type: String,
      default: ''
    },
  },
  computed:{
    spareIncomeProfit(){
      return this.salesMap.spareIncomeProfitData.data;
    },
    serviceIncomeProfit(){
      return this.salesMap.serviceIncomeProfitData.data;
    },
    spareHasNextPage(){
      return this.salesMap.spareIncomeProfitData.hasNextPage;
    },
    serviceHasNextPage(){
      return this.salesMap.serviceIncomeProfitData.hasNextPage;
    }
  },
  setup(props, { emit }) {
    const isEmpty = ref(false);

    const countChart = ref(null);
    const amountChart = ref(null);
    const chartNameList = ref([]);
    
    const isUserTab = computed(() => {
      return props.chartOption?.selectType == 4
    });

    const countInfoData = reactive({
      title: '备件数量统计',
      nameList: [],
      all: 0
    });
    const amountInfoData = reactive({
      title: '备件金额统计',
      nameList: [],
      all: 0
    });

    // 统计模块 是否有下一页
    const hasNextPage = ref(false);
    const chartData = computed(() => {
			return props.sparePartsData;
    })
		watch(chartData, (n,o) => {
      if(!n.countList) clearInfoList();
			initData();
		})

    // 初始化（数量统计 金额统计）数据
    const initData = async () => {
      const { countList, sparePartCount, sparePartAmount } = chartData.value;
      hasNextPage.value = countList?.hasNextPage || false;

      countInfoData.all = sparePartCount;
      amountInfoData.all = sparePartAmount;
      
      let countListData = countList?.list || []
      
      if (isOpenData && isUserTab.value) {
        // countListData = await openDataCanvasConvertData(countListData, 'staffId', 'name')
      } 
      
      chartNameList.value = chartNameList.value.concat(countListData);

      initDrawChart();
    }

    // 初始化图表
    const initChart = () => {
      countChart.value = echarts5.init(document.getElementById('countSummary'), 'shb');
      amountChart.value = echarts5.init(document.getElementById('amountSummary'), 'shb');
      initDrawChart();
    }

    // 生成数量统计 金额统计图表
    const initDrawChart = ()=>{
      drawChart(countChart, countInfoData);
      drawChart(amountChart, amountInfoData);
    }

    // 数量统计 金额统计图表数据
    const drawChart = (dom, dataInfo) => {
      const flag = dataInfo.title === '备件数量统计';
      const type = flag ? 'countValue' : 'amountValue';
      
      const data = chartNameList.value.sort((a,b) => b[type] - a[type]) || [];
      const nameList = [];
      const yAxisList = [];
      data.forEach(x=>{
        nameList.push(x.name);
        yAxisList.push(x[type]);
      })
      dataInfo.nameList = nameList;

      isEmpty.value = !nameList.length;
      if (isEmpty.value) return;

      let start = 0;
      let end = nameList.length - 1;
      if(nameList.length > 10) start = end - 9;

      let yAxisMap = {
        type: 'category',
        data: nameList,
        inverse: true,
        axisLabel: {
          formatter(value) {
            if (value.length > 4) {
              return `${value.substring(0, 4) }...`;
            } 
            return value;
            
          }
        }
      }
      if (isOpenData && isUserTab.value) {
        yAxisMap = {
          type: 'category',
          data: nameList,
          inverse: true
        }
      }
      
      const dataOption = {
        // title: {
        //   text: dataInfo.title,
        //   textStyle: {
        //     fontSize: 14
        //   }
        // },
        grid: {
          top: 20,
          left: 80,
          right: 60,
        },
        dataZoom: [
          {
            type: 'inside'
          },
          {
            type: 'slider',
            yAxisIndex: [0]
          }
        ],
        xAxis: {
          type: 'value'
        },
        yAxis: yAxisMap,
        series: [
          {
            barMaxWidth: '60px',
            data: yAxisList,
            type: 'bar',
            stack: 'Total',
            label: {
              show: true,
              position: 'insideLeft',
              formatter (value) {
                if(dataInfo.title === '备件数量统计'){
                  return `${value?.data}`;
                }
                return `¥${value?.data}`;
              }
            },
          }
        ]
      }
      dom.value.clear();
      dom.value.setOption(dataOption);
      nextTick(() => {
        dom.value.resize()
      })
    }

    // 筛选传值
    const fetchData = (newValue, type)=>{
      clearInfoList();
      emit('fetchChartData', newValue, type);
    }
    // 清空原有数据
    const clearInfoList = ()=>{
      countInfoData.nameList = [];
      amountInfoData.nameList = [];

      chartNameList.value = [];
    }


    /* 收入、利润模块 */
    const detailRadio = ref('0');
    const incomeProfitInfo = computed(() => {
			return props.chartOption;
		})

    // 初始化备件、服务项目明细数据
    const initIncomeProfit = ()=>{
      // 备件明细
      incomeProfitData('spareIncomeProfitData');
      // 服务项目明细
      incomeProfitData('serviceIncomeProfitData');
    }
    const incomeProfitData = (type)=>{
      fetchData({ detailRadio: detailRadio.value }, type);
    }

    // 收入利润按钮切换
    const incomeProfitChange = (e)=>{
      detailRadio.value = e;
      
      emit('fetchTableData', {
        ...incomeProfitInfo.value,
        detailRadio: e
      },'incomeProfit')
    }
    // 明细加载更多 todo
    const categoryMore = value => {
      emit('categoryMore', value)
    }

    // 数量金额统计加载更多
    const loadMore = ()=>{
      incomeProfitInfo.value.page++;

      let params = {
        ...incomeProfitInfo.value,
        page: incomeProfitInfo.value.page
      }
      emit('fetchChartData', params, 'meetSelectType');
    }

    onMounted(() => {
      initChart();
    })

    return {
      isEmpty,
      fetchData,
      detailRadio,
      incomeProfitChange,
      categoryMore,
      hasNextPage,
      loadMore,
      countInfoData,
      amountInfoData,
    };
  },
  components: {
    [StatsChartEmpty.name]: StatsChartEmpty,
    [ChartStockMeetRateSetting.name]: ChartStockMeetRateSetting,
    [BarRankingChart.name]: BarRankingChart,
    [ChartDownload.name]: ChartDownload,
	}
};
</script>

<style lang="scss" scoped>
.chart-card {
  width: 100%;
  text-align: center;

  .summary-box {
    width: 100%;
    min-height: 500px;
    position: relative;

    >div:last-child {
      display: flex;
      flex-direction: column;

      .columnar-chart {
        display: flex;
        justify-content: space-between;

        >div{
          width: 49%;

          .chart-header {
            width: 100%;
            height: 30px;
            line-height: 30px;
            display: flex;
            justify-content: space-between;

            .title {
              font-weight: bold;
              span {
                font-weight: 400;
              }
            }
          }
        }
      }
      
      #countSummary {
        margin-right: 10px;
      }

      .chart-sumary {
        width: 100%;
        height: 500px;
      }

      .load-more {
        height: 40px;
        line-height: 40px;
      }
    }
  }
  
  .bar-chart-box {
    width: 100%;
    min-height: 350px;
    padding-top: 5px;
    position: relative;
    display: flex;
    justify-content: space-between;

    >div {
      width: 49%;
      min-height: 540px;
    }
  }
}

.color9a9a9a{
  color: #9a9a9a;
}
</style>
